import pymongo
import openpyxl
from openpyxl.styles import Font
from openpyxl.styles import PatternFill
from openpyxl.styles import Alignment
import os
'''
这是一段mongodb数据库的操作
'''
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["my_db"]
mycol = mydb["test"]

myquery = {"name":"laoweng1"}


def write(data):
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    
    align=Alignment(horizontal='center',vertical='center')
    
    firstData = data.next()
    keys = list(firstData.keys())
    print(keys)
    
    for i in range(1,len(keys)+1):
        sheet.cell(row=1, column=i).value=keys[i-1]
    

    values = list(firstData.values())
    print(values)
    for index,value in enumerate(values):
        print(i,j)
        sheet.cell(row=2, column=index+1).value=value
    
    row = 2
    
    for i in data:
        print(i)
        i_values = list(i.values())
        for index,value in enumerate(i_values):
            sheet.cell(row=row+1, column=index+1).value=value
        row +=1    
    # 这里根据自己的路径来更改
    workbook.save('C:\\Users\\we\\Desktop\\新建文件夹\\test.xlsx')

result = mycol.find(myquery,{"_id":0,"name":1,"age":1})
print(result)

write(result)